package com.ews.onlineexchange.service;

import java.io.Serializable;

import javax.inject.Inject;
import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.transaction.Transactional;

import org.hibernate.CacheMode;
import org.hibernate.ScrollMode;
import org.hibernate.ScrollableResults;
import org.hibernate.Session;

import com.alibaba.fastjson.JSONObject;
import com.ews.onlineexchange.model.Attachment;
import com.ews.onlineexchange.model.Image;
import com.ews.onlineexchange.util.AttachmentType;
import com.ews.onlineexchange.util.AttachmentUtils;

@Named
@Transactional
public class CleanAttachmentService implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	@Inject
	EntityManager entityManager;
	@Inject
	AttachmentUtils attachmentUtils;
	private final static String GET_ALL_ATTACHMENT = "	"
			+ 	"	SELECT 	attachment	"
			+	"	FROM 	Attachment	attachment ";
	
	public void cleaAttachment() {
		Session session = entityManager.unwrap( Session.class );	
		ScrollableResults sr = session
		        .createQuery(GET_ALL_ATTACHMENT)
		        .setCacheMode( CacheMode.IGNORE )
		        .scroll( ScrollMode.FORWARD_ONLY );	

		long count = 0L;
		while (sr.next()) {
			Object entity = sr.get( 0 );
			if ( !(entity instanceof Attachment ) ) {
				continue;
			}

			Attachment attachment = (Attachment) entity;
			if ( attachment.getFiledata() == null ) {
				continue;
			}
			String fileName = attachment.getFilename();
			JSONObject fileInfo = null;
			
			if ( attachment instanceof Image ) {
				fileInfo = attachmentUtils.getFileInfo(fileName,AttachmentType.Image, attachment.getCreateDate());
			} else {
				fileInfo = attachmentUtils.getFileInfo(fileName,AttachmentType.Attachment, attachment.getCreateDate());
			}
			
			String diskFileName = fileInfo.getString("diskFileName");
			String filepath = fileInfo.getString("filepath");
			attachment.setFilepath(filepath);
			attachment.setDiskFileName(diskFileName);
			if ( attachment instanceof Image ) {
				Image image = (Image) attachment;
				image.setThumbnailPath(attachment.getFilepath());
			}
			attachmentUtils.saveFileToDisk(filepath, attachment.getFiledata());
			entityManager.merge(attachment);
			count++;
			System.out.println( "============================================" + count + "===============================================" );
			if (count % 20 == 0) {
				entityManager.flush();
				entityManager.clear();
			}
		}
		System.out.println( "============================================" + count + "===============================================" );
		entityManager.flush();
		entityManager.clear();
	}
	
}
